﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XingFuStudio.Pioneer.Net;
using XingFuStudio.Pioneer.Entity;
using FluorineFx.IO;
using XingFuStudio.Pioneer.Applications.City.Config;
using XingFuStudio.Pioneer.Applications.City.Entity;
using XingFuStudio.Pioneer.Applications.City.Element;
using XingFuStudio.Pioneer.Applications.City.Config.ConfigKeys;

namespace XingFuStudio.Pioneer.Applications.City.Operation {
    /// <summary>
    /// 商业相关操作
    /// </summary>
    public class Business : OPBase{
        /// <summary>
        /// 调用方法的目标类
        /// </summary>
        private readonly string Target = "CCityAction.callfunc";

        /// <summary>
        /// 创建业务对象
        /// </summary>
        /// <param name="httpManager"></param>
        /// <param name="account"></param>
        /// <param name="city"></param>
        /// <param name="config"></param>
        public Business(HttpManager httpManager, AccountInfo account, CityInfo city, UserConfigSection config)
            : base(httpManager, account, city, config) {
        }

        /// <summary>
        /// 重写操作方法
        /// </summary>
        public override void Operate() {
            base.Operate();

            //初始化值为Null
            object value = null;
            //初始化字典是否有值标识
            bool hasValue = false;

            string message = String.Empty;

            //获取全部商业元素
            var bes = this.city.Elements.Where(s => s is BusinessInfo);
            //遍历商业元素
            foreach (BusinessInfo element in bes) {
                try {
                    //判断是否有值，并获取是否自动接收好友分店供货属性值
                    hasValue = config.ConfigItems.TryGetValue(BusinessConfigKeys.AutoReceive, out value);
                    if (hasValue && Convert.ToBoolean(value)) {
                        if (element.CanReceive) {
                            //接收获物
                            bool result = this.ReceiveDeliver(element, out message);
                            //打印日志
                            this.DoPrintLog(true, message);
                        }
                    }

                    //判断是否有值，并获取是否自动收获属性值
                    hasValue = config.ConfigItems.TryGetValue(BusinessConfigKeys.AutoHarvest, out value);
                    if (hasValue && Convert.ToBoolean(value)) {
                        if (element.CanHarvest && this.city.Energy > 0) {
                            //收获
                            bool result = this.Harvest(element, out message);
                            //打印日志
                            this.DoPrintLog(true, message);

                            //收获完成赋值为可上货
                            element.CanDeliver = true;
                        }
                    }

                    //判断是否有值，并获取是否自动上获属性值
                    hasValue = config.ConfigItems.TryGetValue(BusinessConfigKeys.AutoDeliver, out value);
                    if (hasValue && Convert.ToBoolean(value)) {
                        if (element.CanDeliver && this.city.Goods >= 150) {
                            //上货
                            bool result = this.Deliver(element, out message);
                            //打印日志
                            this.DoPrintLog(true, message);
                        } else if (city.Goods < 150) {
                            //打印日志
                            this.DoPrintLog(true, "货物不足150时停止自动上货，当前货物{0}", city.Goods);
                        }
                    }
                    //判断是否有值，并获取是否自动升级
                    hasValue = config.ConfigItems.TryGetValue(BusinessConfigKeys.AutoUpLevel, out value);
                    if (hasValue && Convert.ToBoolean(value)) {
                        if (element.CanUpLevel(city.UpLevelConfigs, city.UpLevelElements) && this.city.Energy > 0) {
                            //升级
                            bool result = this.UpLevel(element, out message);
                            //打印日志
                            this.DoPrintLog(true, message);
                        }
                    }
                } catch (Exception ex) {
                    this.DoError(ex);
                }
            }
        }

        /// <summary>
        /// 执行收获
        /// </summary>
        /// <param name="cityElemety">操作的元素</param>
        /// <param name="resultMessage">输出参数，用来返回结果信息</param>
        /// <returns></returns>
        public bool Harvest(CityElement cityElemety, out string resultMessage) {
            //声明参数字典
            Dictionary<string, object> dicParam = new Dictionary<string, object>();

            List<object> element = new List<object>();
            List<object> lsElement = new List<object>();

            //Element参数字典
            Dictionary<string, object> dicElement = new Dictionary<string, object>();

            //赋值属性
            dicElement.Add("etype", 1);
            dicElement.Add("helpflag", false);
            dicElement.Add("action", "harvest");
            //元素相当参数
            Dictionary<string, object> dicExData = new Dictionary<string, object>();
            dicExData.Add("etype", new byte[3] { 0x02, 0x04, 0x01 });
            dicExData.Add("buildingType", "2");
            dicExData.Add("eid", cityElemety.ElementId);
            dicElement.Add("exData", dicExData);
            //赋值属性
            dicElement.Add("interval", 5);
            dicElement.Add("orderid", cityElemety.OrderId);
            dicElement.Add("toolkey", "");
            //收获相关属性
            Dictionary<string, object> dicHarvest = new Dictionary<string, object>();
            dicHarvest.Add("xp", 2);
            dicHarvest.Add("cash", 16383);
            if (this.city.Energy < this.minEnergy) {
                dicHarvest.Add("energy", 2);
            }
            dicElement.Add("harvestres", dicHarvest);

            lsElement.Add(dicElement);
            element.Add(lsElement);

            dicParam.Add("element", element);
            dicParam.Add("task", new List<object>());

            //获取AMF数据
            AMFMessage message = this.GetAMFMessage(this.Target, "sync", dicParam);

            //解析数据
            Dictionary<string, object> content = (Dictionary<string, object>)message.Bodies[0].Content;
            Dictionary<string, object> data1 = (Dictionary<string, object>)content["data"];
            object[] element1 = (object[])data1["element"];
            Dictionary<string, object> result1 = (Dictionary<string, object>)element1[0];

            //获取收获是否成功的状态
            bool result = (string)result1["result"] == "succ";

            //如果成功，获取结果信息
            if (result) {
                //获取执行收获后的同步数据
                Dictionary<string, object> sync = (Dictionary<string, object>)result1["sync"];
                //解析经验，金钱，体力等信息
                int exp = Convert.ToInt32(sync["xp"]);
                int cash = Convert.ToInt32(sync["cash"]);
                int energy = Convert.ToInt32(sync["energy"]);
                int goods = Convert.ToInt32(sync["goods"]);
                //赋值结果字符串
                resultMessage = String.Format("收获商店成功。 现金:{3}增加:{0} 经验:{4}增加:{1} 剩余体力:{2}",
                    cash - this.city.Cash, exp - this.city.Exp, energy, cash, exp);
                //更新城市信息
                this.UpdateCityInfo(exp, cash, goods, energy);
            } else {
                resultMessage = String.Format("收获商店失败，{0}！", (string)result1["msg"]);
            }

            return result;
        }

        /// <summary>
        /// 执行上货
        /// </summary>
        /// <param name="cityElemety">操作的元素</param>
        /// <param name="resultMessage">输出参数，用来返回结果信息</param>
        /// <returns></returns>
        public bool Deliver(CityElement cityElemety, out string resultMessage) {
            //声明参数字典
            Dictionary<string, object> dicParam = new Dictionary<string, object>();

            List<object> element = new List<object>();
            List<object> lsElement = new List<object>();

            //Element参数字典
            Dictionary<string, object> dicElement = new Dictionary<string, object>();

            //赋值属性
            dicElement.Add("orderid", cityElemety.OrderId);
            dicElement.Add("interval", 5);
            //元素相当参数
            Dictionary<string, object> dicExData = new Dictionary<string, object>();
            dicExData.Add("etype", 1);
            dicExData.Add("eid", cityElemety.ElementId);
            dicExData.Add("buildingType", "1");
            dicElement.Add("exData", dicExData);

            dicElement.Add("etype", new byte[3] { 0x0a, 0x04, 0x01 });
            dicElement.Add("action", "deliver");

            lsElement.Add(dicElement);
            element.Add(lsElement);

            dicParam.Add("element", element);
            dicParam.Add("task", new List<object>());

            //获取AMF数据
            AMFMessage message = this.GetAMFMessage(this.Target, "sync", dicParam);

            //解析数据
            Dictionary<string, object> content = (Dictionary<string, object>)message.Bodies[0].Content;
            Dictionary<string, object> data1 = (Dictionary<string, object>)content["data"];
            object[] element1 = (object[])data1["element"];
            Dictionary<string, object> result1 = (Dictionary<string, object>)element1[0];

            //获取收获是否成功的状态
            bool result = (string)result1["result"] == "succ";

            //如果成功，获取结果信息
            if (result) {
                //获取执行收获后的同步数据
                Dictionary<string, object> sync = (Dictionary<string, object>)result1["sync"];
                //解析经验，金钱，体力等信息
                int exp = Convert.ToInt32(sync["xp"]);
                int cash = Convert.ToInt32(sync["cash"]);
                int energy = Convert.ToInt32(sync["energy"]);
                int goods = Convert.ToInt32(sync["goods"]);
                //赋值结果字符串
                resultMessage = String.Format("上货成功。 上货数量:{0} 剩余货物:{1}", this.city.Goods - goods, goods);
                //更新城市信息
                this.UpdateCityInfo(exp, cash, goods, energy);
            } else {
                resultMessage = String.Format("上货失败，{0}！", (string)result1["msg"]);
            }

            return result;
        }

        /// <summary>
        /// 执行收取好友供的货
        /// </summary>
        /// <param name="cityElemety">操作的元素</param>
        /// <param name="resultMessage">输出参数，用来返回结果信息</param>
        /// <returns></returns>
        public bool ReceiveDeliver(CityElement cityElemety, out string resultMessage) {
            //声明参数字典
            Dictionary<string, object> dicParam = new Dictionary<string, object>();

            List<object> element = new List<object>();
            List<object> lsElement = new List<object>();

            //Element参数字典
            Dictionary<string, object> dicElement = new Dictionary<string, object>();

            //赋值属性
            dicElement.Add("orderid", cityElemety.OrderId);
            dicElement.Add("interval", 5);
            dicElement.Add("etype", 1);
            dicElement.Add("action", "takedeliver");

            lsElement.Add(dicElement);
            element.Add(lsElement);

            dicParam.Add("element", element);

            //获取AMF数据
            AMFMessage message = this.GetAMFMessage(this.Target, "sync", dicParam);

            //解析数据
            Dictionary<string, object> content = (Dictionary<string, object>)message.Bodies[0].Content;
            Dictionary<string, object> data1 = (Dictionary<string, object>)content["data"];
            object[] element1 = (object[])data1["element"];
            Dictionary<string, object> result1 = (Dictionary<string, object>)element1[0];

            //获取收获是否成功的状态
            bool result = (string)result1["result"] == "succ";

            //如果成功，获取结果信息
            if (result) {
                //获取执行收获后的同步数据
                Dictionary<string, object> sync = (Dictionary<string, object>)result1["sync"];
                //解析经验，金钱，体力等信息
                int exp = Convert.ToInt32(sync["xp"]);
                int cash = Convert.ToInt32(sync["cash"]);
                int energy = Convert.ToInt32(sync["energy"]);
                int goods = Convert.ToInt32(sync["goods"]);
                //赋值结果字符串
                resultMessage = String.Format("接收获物成功。 剩余货物:{0} 剩余体力:{1}", goods, energy);
                //更新城市信息
                this.UpdateCityInfo(exp, cash, goods, energy);
            } else {
                resultMessage = String.Format("接收获物失败，{0}！", (string)result1["msg"]);
            }

            return result;
        }
    }
}
